package org.jeecgframework.web.controller;

import com.alibaba.fastjson.JSONObject;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.pojo.vo.WechatUserResponse;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

/**
 * Created by red on 2016/9/22.
 */
@Controller
@RequestMapping("/wecharInter")
public class WechatController {

    @Autowired
    private SystemService systemService;

    public static final String REQUESTKEY = "dc2eeb18955d46f7b6d6aa726520f124";
    public static final String SUC_FLAG = "y";
    public static final String FAIL_FLAG = "n";

    public String genOpenId(String openId){
        return openId;
    }

    public boolean ifValidRequestKey(String key){
        return REQUESTKEY.equals(key);
    }

    /**
     * 获取单个用户信息
     * */
    @RequestMapping(params = "getSingleUser")
    @ResponseBody
    public WechatUserResponse getSingleUser(@RequestParam("key") String key,@RequestParam("openId") String openId){
        WechatUserResponse response = new WechatUserResponse();
        response.setState(SUC_FLAG);
        if(!ifValidRequestKey(key)){
            response.setState(FAIL_FLAG);
            response.setMsg("key is invalid");
            return response;
        }
        List<TSUser> users = systemService.findHql("from TSUser where openId=?",genOpenId(openId));
        if(users.size() == 0){
            response.setMsg("user not exists");
            return response;
        }else{
            return generateUser(users.get(0),response);
        }
    }

    /**
     * 获取批量用户信息
     * */
    @RequestMapping(params = "getBatchUser")
    @ResponseBody
    public Map getSingleUser(@RequestParam("key") String key){
        Map result = new HashMap();
        result.put("state",SUC_FLAG);
        WechatUserResponse response = new WechatUserResponse();
        response.setState(SUC_FLAG);
        if(!ifValidRequestKey(key)){
            result.put("state",FAIL_FLAG);
            result.put("msg","key is invalid");
            return result;
        }
        List<TSUser> users = systemService.findHql("from TSUser where authenticationLevel in ('1','2','3')");
        if(users.size() == 0){
            result.put("state",FAIL_FLAG);
            result.put("state","user not exists");
            return result;
        }else{
            List<WechatUserResponse> repse = new ArrayList<WechatUserResponse>();
            for(TSUser u : users){

                repse.add(generateUser(u,new WechatUserResponse()));
            }
            result.put("data",repse);
            return result;
        }
    }

    /**
     * 锁定用户
    * */
    @RequestMapping(params = "lockUser")
    @ResponseBody
    public WechatUserResponse lockUser(@RequestParam("key") String key,@RequestParam("openId") String openId){
        WechatUserResponse response = new WechatUserResponse();
        response.setState(SUC_FLAG);
        if(!ifValidRequestKey(key)){
            response.setState(FAIL_FLAG);
            response.setMsg("key is invalid");
            return response;
        }
        List<TSUser> users = systemService.findHql("from TSUser where openId=?",genOpenId(openId));
        if(users.size() == 0){
            response.setMsg("user not exists");
            return response;
        }else{
            users.get(0).setStatus((short)0);
            return response;
        }
    }


    public WechatUserResponse generateUser(TSUser user,WechatUserResponse response){
        response.setIsRegister(FAIL_FLAG);
        response.setIsAuthentication(FAIL_FLAG);
        switch (oConvertUtils.getString(user.getAuthenticationLevel())){
            case "1":
            case "3":
                response.setIsRegister(SUC_FLAG);
                break;
            case "2":
                response.setIsAuthentication(SUC_FLAG);
                break;
        }

        response.setUserName(user.getUserName());
        response.setRealName(user.getRealName());
        response.setOpenId(user.getOpenId());
        response.setUserState("0".equals(oConvertUtils.getString(user.getStatus()))?"1":"0");

        List<ZyContactsEntity> cts = systemService.findByProperty(ZyContactsEntity.class,"tsBaseUser.id",user.getId());
        if(cts.size() > 0 && cts.get(0).getBelongCinema() != null){
            response.setCinemaName(cts.get(0).getBelongCinema().getName());
        }
        return response;
    }

    /**
     * 微信用户注册
     */
    @RequestMapping(params = "wxUserRegister")
    @ResponseBody
    public WechatUserResponse wxUserRegister(HttpServletRequest request) throws Exception {
        System.out.println("用户注册");
        TSLog log=new TSLog();
        log.setLogcontent("调用微信用户认证注册接口");
        WechatUserResponse response = new WechatUserResponse();
        String param= null;
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            param= jsonObject.toJSONString();
            System.out.println("param:"+param);
            System.out.println("jsonObject:"+jsonObject);
        String realName=jsonObject.getString("realName");
        String key=jsonObject.getString("key");
        String openId=jsonObject.getString("openId");
        String phoneNumber=jsonObject.getString("phoneNumber");
        String headImg=jsonObject.getString("headImg");
        String cinemaName=jsonObject.getString("cinemaName");
        response.setState(SUC_FLAG);
        if (!ifValidRequestKey(key)) {
            response.setState(FAIL_FLAG);
            response.setMsg("key is invalid");
        }
//        String openId="oacqX1XUgi_YdMy75LvdYUveLBD0";
//        String phoneNumber="17610409863";
//        String cinemaName="测试";
//        String realName="马宏刚";
//        String headImg="http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoA0cc20qpvKhibBbkcDaxHz4lesxiaInzdKgqMHL6lHIQVQCd7nNdbFKkVEdLVvNoa9g84U1OjsXlg/132";

        List<TSUser> validUserList = systemService.findHql("from TSUser where openId = ?", openId);
        if (validUserList.size() > 0) {
            response.setState(FAIL_FLAG);
            response.setMsg("您已经注册过帐号，请重新登录");
            System.out.println("您已经注册过帐号，请重新登录");
            if (validUserList.get(0).getStatus().equals(Globals.User_Forbidden)) {
                response.setMsg("您的帐号已被停用");
            }
            return response;
        }


        ZyCinemaEntity cinema=null;
        List<ZyCinemaEntity> cinemaList=systemService.findHql("from ZyCinemaEntity where name='"+cinemaName+"'");
        if(cinemaList!=null && cinemaList.size()>0){
            cinema=cinemaList.get(0);
        }
        TSUser user=null;
        ZyContactsEntity contacts=null;
        List<ZyContactsEntity> contactsList = systemService.findHql("from ZyContactsEntity where cellphone1 = ?", phoneNumber);
        //根据手机号判断是否有该用户
        List<TSUser> userList=systemService.findHql("from TSUser where mobilePhone=?",phoneNumber);
        //如果有该用户
        if(userList!=null && userList.size()>0){
            System.out.println("根据电话查询到了用户");
            user=userList.get(0);
            if(user.getAuthenticationLevel()!=null && !user.getAuthenticationLevel().equals("")){
                //如果用户级别为钻石，将该用户的级别和影院设备列表同步给微信端
                if(user.getAuthenticationLevel().equals("2")){
                    System.out.println("用户级别为钻石");
                    List<Map<String,Object>> equipmentList=null;
                    List<ZyContactsEntity> contactList = systemService.findHql("from ZyContactsEntity where tsBaseUser.id = ?", userList.get(0).getId());
                    if(contactList.size() > 0 && StringUtil.isNotEmpty(contactList.get(0).getBelongCinema())){
                        String sql="SELECT eq.sn AS sn,eq.item AS item,t.type_desc AS type  FROM `zy_equipment_spare` eq LEFT JOIN zy_equipment_type t ON t.id=eq.type where eq.is_spare = false and eq.belong_cinema_id ='"+contactList.get(0).getBelongCinema().getId()+"'";
                        equipmentList=systemService.findForJdbc(sql);
                        System.out.println("esList:"+equipmentList);
                    }

                    //由于换了一个公众号，原用户的openId已经和现在不一样，所以要更新一下openId
                    String oldOpenId=user.getOpenId();
                    List<CbsWxUserBindEntity> wxUserBindList=systemService.findHql("from CbsWxUserBindEntity where openId=?",oldOpenId);
                    if(wxUserBindList!=null && wxUserBindList.size()>0){
                        CbsWxUserBindEntity wxUserBind=wxUserBindList.get(0);
                        wxUserBind.setOpenId(openId);
                        systemService.saveOrUpdate(wxUserBind);
                    }
                    user.setOpenId(openId);
                    systemService.saveOrUpdate(user);

                    log.setLogcontent("调用微信用户认证注册接口修改老用户的openId，用户原openId为"+oldOpenId+",新openId为"+openId+"");

                    response.setEquipmentList(equipmentList);
                    response.setAuthenticationLevel("2");
                }
                //如果用户级别为银牌或者金牌，将影院名称记录至联系人的注册影院列（新加列）中
                if(user.getAuthenticationLevel().equals("1") || user.getAuthenticationLevel().equals("0") || user.getAuthenticationLevel().equals("4")){
                    System.out.println("用户级别为银牌");
                    String oldOpenId=user.getOpenId();
                    user.setAuthenticationLevel("1");
                    user.setOpenId(openId);
                    systemService.saveOrUpdate(user);
                    log.setLogcontent("调用微信用户认证注册接口修改老用户的openId，用户原openId为"+oldOpenId+",新openId为"+openId+"");
                    if(contactsList!=null && contactsList.size()>0){
                        contacts=contactsList.get(0);
                        contacts.setTsBaseUser(user);
                        contacts.setCinemaName(cinemaName);
                        // modify start 181102 无系统影院id时，不更新联系人所属影院
                        if(cinema != null){
                        	contacts.setBelongCinema(cinema);
                        }
                        // modify end 181102
                        systemService.saveOrUpdate(contacts);
                    }else{
                        List<ZyContactsEntity> contactsEntities=systemService.findHql("from ZyContactsEntity where tsBaseUser.id=?",user.getId());
                        if(contactsEntities!=null && contactsEntities.size()>0){
                            contacts=contactsEntities.get(0);
                            contacts.setCinemaName(cinemaName);
                            contacts.setTsBaseUser(user);
                            /*更新联系人表中真是姓名*/
                            contacts.setName(realName);
                            // modify start 181102 无系统影院id时，不更新联系人所属影院
                            if(cinema != null){
                            	contacts.setBelongCinema(cinema);
                            }
                            // modify end 181102
                            systemService.saveOrUpdate(contacts);
                        }else{
                            contacts=new ZyContactsEntity();
                            contacts.setTsBaseUser(user);
                            contacts.setType(StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT);
                            contacts.setName(realName);
                            contacts.setCellphone1(phoneNumber);
                            contacts.setSource("微信注册");
                            contacts.setIsDelete("0");
                            contacts.setCinemaName(cinemaName);
                            contacts.setCreateDate(new Date());
                            contacts.setBelongCinema(cinema);
                            contacts.setPosition(StaticValue.DIC_CONTACT_POSITION_C_TECHNICIAN);
                            contacts.setState(StaticValue.DIC_ENGINEER_STATE_ONJOB);
                            systemService.save(contacts);
                        }
                    }
                }

            }else{
                String oldOpenId=user.getOpenId();
                user.setAuthenticationLevel("1");
                user.setOpenId(openId);
                systemService.saveOrUpdate(user);
                log.setLogcontent("调用微信用户认证注册接口将非微信老用户更新为微信用户，openId为"+openId+"");
                if(contactsList!=null && contactsList.size()>0){
                    contacts=contactsList.get(0);
                    contacts.setTsBaseUser(user);
                    contacts.setCinemaName(cinemaName);
                    // modify start 181102 无系统影院id时，不更新联系人所属影院
	                if(cinema != null){
	                    contacts.setBelongCinema(cinema);
	                }
	                // modify end 181102
                    systemService.saveOrUpdate(contacts);
                }else{
                    List<ZyContactsEntity> contactsEntities=systemService.findHql("from ZyContactsEntity where tsBaseUser.id=?",user.getId());
                    if(contactsEntities!=null && contactsEntities.size()>0){
                        contacts=contactsEntities.get(0);
                        contacts.setCinemaName(cinemaName);
                        contacts.setTsBaseUser(user);
                        /*更新联系人表中真是姓名*/
                        contacts.setName(realName);
                        // modify start 181102 无系统影院id时，不更新联系人所属影院
    	                if(cinema != null){
    	                	contacts.setBelongCinema(cinema);
    	                }
    	                // modify end 181102
                        systemService.saveOrUpdate(contacts);
                    }else{
                        contacts=new ZyContactsEntity();
                        contacts.setTsBaseUser(user);
                        contacts.setType(StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT);
                        contacts.setName(realName);
                        contacts.setCellphone1(phoneNumber);
                        contacts.setSource("微信注册");
                        contacts.setIsDelete("0");
                        contacts.setCinemaName(cinemaName);
                        contacts.setCreateDate(new Date());
                        contacts.setBelongCinema(cinema);
                        contacts.setPosition(StaticValue.DIC_CONTACT_POSITION_C_TECHNICIAN);
                        contacts.setState(StaticValue.DIC_ENGINEER_STATE_ONJOB);
                        systemService.save(contacts);
                    }
                }
            }

        }else{
            System.out.println("根据电话没有查询到用户");
            //如果没有用户
            if (contactsList.size() > 0 && StringUtil.isNotEmpty(contactsList.get(0).getTsBaseUser())) {
                user = systemService.get(TSUser.class, contactsList.get(0).getTsBaseUser().getId());
            } else {
                user = new TSUser();
            }

            String userName = PinyinUtil.getPinYin(realName);
            user.setRealName(realName);

//            List<TSUser> repeatUserList = systemService.findHql("from TSUser where userName = ?", userName);
//            if (repeatUserList.size() > 0) {
//                Integer num = repeatUserList.size() == 1 ? 1 : repeatUserList.size() + 1;
//                userName = userName + num;
//            }

            //防止用户名重复
            while(true){
                List<TSUser> repeatUserList = systemService.findHql("from TSUser where userName = ?", userName);
                if (repeatUserList.size() > 0) {
                    Integer num = repeatUserList.size() == 1 ? 1 : repeatUserList.size() + 1;
                    userName = userName + num;
                    System.out.println("userName:"+userName);
                }else{
                    break;
                }
            }
            System.out.println("userNameFinal:"+userName);

            user.setUserName(userName);
            user.setPassword(PasswordUtil.encrypt(user.getUserName(), "123456", PasswordUtil.getStaticSalt()));
            user.setAppPassword(user.getPassword());
            user.setStatus(Globals.User_Normal);
            user.setActivitiSync((short) 0);
            user.setOpenId(openId);
            user.setAuthenticationLevel("1");
            user.setMobilePhone(phoneNumber);
            user.setUserKey("");
            user.setWxHeadImgUrl(headImg);
            systemService.save(user);
            log.setLogcontent("调用微信用户认证注册接口,注册新用户，openId为"+openId+"");
            TSRole role = systemService.findUniqueByProperty(TSRole.class, "roleCode", "wxrole");
            if (role != null) {
                TSRoleUser rUser = new TSRoleUser();
                rUser.setTSUser(user);
                rUser.setTSRole(role);
                systemService.save(rUser);
            }
            if (contactsList.size() > 0) {
                contacts = contactsList.get(0);
                contacts.setTsBaseUser(user);
                /*更新联系人表中真是姓名*/
                contacts.setName(realName);
                contacts.setCinemaName(cinemaName);
                // modify start 181102 无系统影院id时，不更新联系人所属影院
                if(cinema != null){
                	contacts.setBelongCinema(cinema);
                }
                // modify end 181102
                systemService.saveOrUpdate(contacts);
            } else {
                contacts = new ZyContactsEntity();
                contacts.setType(StaticValue.DIC_CONTACT_TYPE_CINEMA_CONTACT);
                contacts.setName(realName);
                contacts.setCellphone1(phoneNumber);
                contacts.setSource("微信注册");
                contacts.setIsDelete("0");
                contacts.setTsBaseUser(user);
                contacts.setCinemaName(cinemaName);
                contacts.setCreateDate(new Date());
                contacts.setBelongCinema(cinema);
                contacts.setPosition(StaticValue.DIC_CONTACT_POSITION_C_TECHNICIAN);
                contacts.setState(StaticValue.DIC_ENGINEER_STATE_ONJOB);
                systemService.save(contacts);
            }
        }
//        systemService.addLog("调用微信用户认证注册接口"，"","");

        log.setLoglevel(Globals.Log_Type_UPDATE);
        log.setNote("");
        log.setOperatetime(DateUtils.gettimestamp());
        log.setTSUser(user);
        systemService.save(log);
        response.setAuthenticationLevel(user.getAuthenticationLevel());
        return response;
    }


    /**
     * 获取该钻石用户所属影院的备件信息列表
     * */
    @RequestMapping(params = "wxUserEquipmentList")
    @ResponseBody
    public Map wxUserEquipmentList(HttpServletRequest request){
        Map result = new HashMap();
        result.put("state",SUC_FLAG);
        String param= null;
        try{
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            param= jsonObject.toJSONString();
            System.out.println("param:"+param);
            System.out.println("jsonObject:"+jsonObject);
            String openId=jsonObject.getString("openId");
            System.out.println("openId:"+openId);
            List<TSBaseUser> userList=systemService.findHql("from TSBaseUser where openId=?",openId);
            List<Map<String,Object>> equipmentList=new ArrayList<>();
            if(userList!=null && userList.size()>0 && userList.get(0)!=null){
                List<ZyContactsEntity> contactList = systemService.findHql("from ZyContactsEntity where tsBaseUser.id = ?", userList.get(0).getId());
                if(contactList.size() > 0 && StringUtil.isNotEmpty(contactList.get(0).getBelongCinema())){
                    String sql="SELECT eq.sn AS sn,eq.item AS item,t.type_desc AS type  FROM `zy_equipment_spare` eq LEFT JOIN zy_equipment_type t ON t.id=eq.type where eq.is_spare = false and eq.belong_cinema_id ='"+contactList.get(0).getBelongCinema().getId()+"'";
                    equipmentList=systemService.findForJdbc(sql);
                    result.put("equipmentList",equipmentList);
                    System.out.println("esList:"+equipmentList);
                }
            }
        }catch (Exception e){
            result.put("state",FAIL_FLAG);
        }
        return result;
    }


    /*
    * 获取用户openId并存到session中(未用到)
    * */

    @RequestMapping(params = "saveOpenIdToSession")
    @ResponseBody
    public Map saveOpenIdToSession(HttpServletRequest request){
        Map result = new HashMap();
        result.put("state",SUC_FLAG);
        String param= null;
        try{
            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            param= jsonObject.toJSONString();
            System.out.println("param:"+param);
            System.out.println("jsonObject:"+jsonObject);
            String openId=jsonObject.getString("openId");
            System.out.println("openId:"+openId);

            request.getSession().setAttribute("openId",openId);
        }catch (Exception e){
            result.put("state",FAIL_FLAG);
        }
        return result;
    }
}
